<?php

namespace support\utils;

class Arr
{
    public static function tree(array $arr, $parentKey = 'parent_id', $idKey = 'id', $childKey = 'children', $keepParent = false)
    {
        $res = [];
        if (empty($arr)) {
            return $res;
        }
        foreach($arr as $item) {
            $pid = $item[$parentKey];
            if (!isset($res[$pid])) {
                $res[$pid] = [];
            }
            if (!$keepParent) {
                unset($item[$parentKey]);
            }
            array_push($res[$pid], $item);
        }
        ksort($res);
        $tree = $res[0];
        foreach($tree as &$value) {
            self::getChildList($value, $res, $idKey, $childKey);
        }
        return $tree;
    }

    public static function getChildList(&$tree, $list, $idKey = 'id', $childKey = 'children')
    {
        $tree[$childKey] = $list[$tree[$idKey]] ?? [];
        for ($i=0; $i < count($tree[$childKey]); $i++) {
            self::getChildList($tree[$childKey][$i], $list, $idKey, $childKey);
        }
    }
}